<template>
	<view class="mainbgc" v-if="pageShow">
		<header-top :messageInfo="{typeFlag:true,message:'盘点单',liner:false}">
			<view class="rightmsg" slot="rightmsg">
				<view class="rightmsg_content flexleft" @click="startPrint(102)" v-if="pd_status==20">
					<image class="img" src="../../../static/image/system/my2.png" mode=""></image>
				</view>
				<view class="rightmsg_content flexleft" v-if="pd_status==10">
					<view class="diandiandian" @click="dian" >
						<view class="selectcontent " v-show="selectshow">
							<view class="topbox itemselect" @click="changestatus(0)">
								<view class="duihao" v-show="status==0"></view>
								<view>全部</view>
							</view>
							<view class="topbox itemselect" @click="changestatus(10)">
								<view class="duihao" v-show="status==10"></view>
								<view>已盘点</view>
							</view>
							<view class="topbox itemselect" @click="changestatus(20)">
								<view class="duihao" v-show="status==20"></view>
								<view>未盘点</view>
							</view>
							<view class="sanjiao"></view>
						</view>
					</view>
				</view>
			</view>
		</header-top>
		<view class="mainpadding flexbetween margin_top ffffff">
			<view class="strongtext">仓库</view>
			<view class="strongtext">{{dataAll.warehouse.name}}</view>
		</view>
		<!-- 商品信息 -->
		<view class="shangpinbox">
			<view class="mainpadding  margin_top ffffff">
				<!-- 选择商品 -->
				<view class="flexbetween">
					<view class="xuanzsp">选择盘点商品</view>
					<view class="flexleft">
						<view class="xuanzsp" @click="tztjsp">请选择</view>
						<view class="lanseyoujt" @click="tztjsp"></view>
						<view class="line"></view>
						<view class="scan2" @click="scanbarCode()"></view>
					</view>
				</view>
				<!-- 商品 -->
				<template v-if="dataAll.pdgoods">
					<view class="xiabk margin_top" v-for="item in dataAll.pdgoods" :key="item.id" @click="xgdjmx(item)">
						<view class="flexbetween">
							<view class="strongtext">{{item.goodsinfo.name}}</view>
							<view class="flexright">
								<!-- 10=未盘点,20=盘亏,30=盘平,40=盘盈 -->
								<view class="lablehuang margin_right2" v-show="item.status==10">未盘</view>
								<view class="lablehong margin_right2" v-show="item.status==20">盘亏</view>
								<view class="lablelan margin_right2" v-show="item.status==30">盘平</view>
								<view class="lablelv margin_right2" v-show="item.status==40">盘盈</view>
								<view class="righticon margin_right2"></view>
							</view>
							
						</view>
						<view class="huisetext margin_top">当前库存：{{item.total_stock}}</view>
						<view class="huisetext margin_top">盘点库存：
						<text v-show="item.big_unit_stock>0">{{item.big_unit_stock}}{{item.goodsinfo.biggoodsunit.name}}</text>
						<text v-show="item.middle_unit_stock>0">{{item.middle_unit_stock}}{{item.goodsinfo.middlegoodsunit.name}}</text>
						<text v-show="item.small_unit_stock>0">{{item.small_unit_stock}}{{item.goodsinfo.smallgoodsunit.name}}</text>
						</view>
						<view class="flexright margin_top" v-if="pd_status==10">
							<view class="shanchu" @click.stop="delItem(item.id)"></view>
						</view>
					</view>
				</template>
				
			</view>
		</view>
		<!-- 底部 -->
		<view class="dibubox" >
			<view class="onebox flexcenter flex_wrap">
				<view class="huangse">共{{dataAll.pdinfo.total_goods_num}}件，</view>
				<view class="huangse">已盘{{dataAll.pdinfo.yp_goods_num}}件，</view>
				<view class="huangse" style="color: #ff0000;">未盘{{dataAll.pdinfo.wp_goods_num}}件</view>
			</view>
			<view class="mainpadding ffffff flexbetween" >
				<view class="qiantui reset flexcenter" v-if="pd_status==10" @click="fq">放弃盘点</view>
				<view class="qiantui greenbtn flexcenter" v-if="pd_status==10" @click="wancpd">完成盘点</view>
			</view>
		</view>
		<moDal :message="{modalShow:modal.modalShow,title:modal.title}" @modalSure="modalSure"></moDal><!-- 模态框 -->
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	const tsc = require("@/util/ble/tsc.js");
	const esc = require("@/util/ble/esc.js");
	const encode = require("@/util/ble/encoding.js");
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				selectshow: false,
				listid:"3",
				dataAll:{},
				status:0,//0全部，1未盘点，2已盘点
				// 模态框
				modal: {
					modalShow: false,
					title: "",
				},
				currentId:"",
				pd_status:"10",//盘点状态 10盘点中，20盘点完成
				pageShow:false,
				// 打印机技术参数
				sendContent: "../../../static/image/news/boy.png",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '../../static/img/abc_ic_star_black_16dp.png',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				// 打印机技术结束
			}
		},

		onLoad(options) {
			this.listid = options.id
		// 打印机
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// 打印机结束
		},
		// 打印机开始
		computed: mapState(['sysinfo', 'Bluetooth']),
		onReady() {
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
				list[j] = i;
				j++
			}
			for (let i = 1; i < 10; i++) {
				numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
		},
		// 打印机结束
		onShow() {
			this.init()
			// 打印机开始
			let that = this;
			let width;
			let height;
			uni.getImageInfo({
				src: that.imageSrc,
				success(res) {
					console.log(res.width)
					console.log(res.height)
					width = res.width
					height = res.height
					that.canvasWidth = res.width;
					that.canvasHeight = res.height;
				}
			})
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			ctx.drawImage(this.imageSrc, 0, 0, width, height);
			ctx.draw();
			// 打印机结束
		},
		methods: {
			// 打印机开始
			receiptTest() {
				// this.selectshow = false
				var that = this;
				var canvasWidth = that.canvasWidth
				var canvasHeight = that.canvasHeight
				var command = esc.jpPrinter.createNew()
				command.init()
				// 标题
				command.bold(1); //加粗
				command.setFontSize(16); //字体大小
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.rowSpace(100);
				command.setText("盘点单");
				command.setPrint();
				command.rowSpace(60); //行间距
				command.bold(0); //取消加粗
				command.setFontSize(0); //正常字体
				// 内容
				command.bold(0); //加粗
				command.setSelectJustification(0) //居中0左对齐1居中对齐2右对齐
				command.setText("订单时间：" + that.dataAll.pdinfo.createtime_text);
				command.setPrint();
				command.setText("订单编号：" + that.dataAll.pdinfo.order_no);
				command.setPrint();
				command.setText("经办人：" + that.dataAll.staff.username+"（"+that.dataAll.staff.mobile+"）" + "  仓库："+that.dataAll.warehouse.name);
				command.setPrint();
				// 表格                                                                        
				command.rowSpace(80); //间距
				command.bold(5); //加粗
				command.setText("商品名称");
				command.setAbsolutePrintPosition(170);
				command.setText("当前库存");
				command.setAbsolutePrintPosition(270);
				command.setText("盘点库存");
				command.setAbsolutePrintPosition(380);
				command.setText("相差库存");
				command.setAbsolutePrintPosition(480)
				command.setText("状态");
				command.setPrint()
				command.bold(0); //加粗
				that.dataAll.pdgoods.forEach(item=>{
					command.setText(item.goodsinfo.name);
					command.setAbsolutePrintPosition(170);
					command.setText(item.total_stock);
					command.setAbsolutePrintPosition(270);
					let text = ""
					if(item.big_unit_stock!=-1){
						text = text+"大"+item.big_unit_stock
						pdnum = item.big_unit_stock
					}
					if(item.middle_unit_stock!=-1){
						text = text+"中"+item.middle_unit_stock
					}
					if(item.small_unit_stock!=-1){
						text = text+"小"+item.small_unit_stock
					}
					command.setText(text);
					command.setAbsolutePrintPosition(380);
					command.setText(item.xc_stock);
					command.setAbsolutePrintPosition(480);
					command.setText(item.status==10?"未盘":item.status==20?"盘亏":item.status==30?"盘平":"盘盈");
					command.setPrint()
				})
				command.bold(5); //加粗
				command.setText("共计" + that.dataAll.pdinfo.total_goods_num+"商品，已盘"+that.dataAll.pdinfo.yp_goods_num+"，未盘"+that.dataAll.pdinfo.wp_goods_num);
				command.setPrint()
				command.setText("签字：");
				command.setPrint()
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.setText("询博技术支持");
				command.setPrintAndFeedRow(3);
				that.isReceiptSend = true;
				that.prepareSend(command.getData());
			
			
			},
			
			//准备发送，根据每次发送字节数来处理分包数量
			prepareSend(buff) {
				console.log(buff);
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				console.log(looptime + "---" + lastData)
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = that.Bluetooth;
			
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log(res)
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {
						currentTime++
						if (currentTime <= loopTime) {
							that.currentTime = currentTime;
							that.Send(buff)
						} else {
							//  uni.showToast({
							// title: '已打印第' + currentPrint + '张',
							//  })
							if (currentPrint == printNum) {
								that.looptime = 0;
								that.lastData = 0;
								that.currentTime = 1;
								that.isReceiptSend = false;
								that.isLabelSend = false;
								that.currentPrint = 1;
							} else {
								currentPrint++;
								that.currentPrint = currentPrint;
								that.currentTime = 1;
								that.Send(buff)
							}
						}
					}
				})
			},
			// 打印机结束
			// 详情接口
			init() {
				httpRequest.request('/dhtapi/Warehouse/pdDetail', 'GET', {
					warehouse_pd_id: this.listid,
					status:this.status
				}, false, false, true).then(res => {
					if (res.code == 1) {
						this.dataAll = res.data
						this.pd_status = res.data.pdinfo.status
						this.pageShow = true
					}
				})
			},
			changestatus(Val){
				this.status = Val
				this.init()
			},
			//跳转修改盘点单
			xgdjmx(item) {
				if(this.pd_status==20){
					httpRequest.toast("已完成盘点，不可操作！")
					return false
				}
				uni.navigateTo({
					url: '/pages/workbench/kucun/pandiandbj?id=' + item.id
				})
				
			},
			delItem(id) {
				this.modal.modalShow = true
				this.modal.title = "确定删除当前内容吗"
				this.currentId = id
			},
			fq(){
				this.modal.modalShow = true
				this.modal.title = "确定放弃盘点当前仓库吗?"
			},
			startPrint(qxpdid) {
				if (!httpRequest.qxpd(qxpdid, this.$store.state.userInfo.ability_rule_ids)) {
					return false
				}
				let that = this
				uni.showActionSheet({
					itemList: ['云打印机', '蓝牙打印机'],
					success: function(res) {
						// 选择云打印机走0
						if (res.tapIndex == 0) {
							that.modal.title = "请再次确认打印！"
							that.modalSure()
						}
						// 选择蓝牙打印机走1
						if (res.tapIndex == 1) {
							that.receiptTest()
						}
					},
					fail: function(res) {}
				});
			},
			modalSure() {
				if(this.modal.title == "确定删除当前内容吗"){
					httpRequest.request('/dhtapi/Warehouse/delPdGoods', 'POST', {
						id: this.currentId
					}, false, false, true).then(res => {
						httpRequest.toast(res.msg)
						if (res.code == 1) {
							this.init()
						}
					})
				}else if(this.modal.title == "确定放弃盘点当前仓库吗?"){
					this.fangqck()
				}else if (this.modal.title == "请再次确认打印！") {
					uni.showLoading({
						mask: true,
						title: "发送数据中"
					})
					let url = "/dhtapi/Warehouse/dyPdDetail"
					httpRequest.request(url, 'GET', {
						warehouse_pd_id: this.listid,
					}, false, false, true).then(res => {
						uni.hideLoading()
						httpRequest.toast(res.msg)
					}).catch(err => {
						httpRequest.toast(err.msg);
					})
				}
				
			},
			
			// 跳转添加商品
			tztjsp() {
				if(this.pd_status==20){
					httpRequest.toast("已完成盘点，不可操作！")
					return false
				}
				let _this = this
				let data = {
					type: 8,
					warehouse_id:this.dataAll.warehouse.id,
					pd_id:this.listid,
					keyword:""
				}
				uni.navigateTo({
					url: '/pages/workbench/xiaoshou/tianjspxsdd?getmsg=' +
						encodeURIComponent(JSON.stringify(data))
				})
			},
			scanbarCode() {
				let that = this
				if(that.pd_status==20){
					httpRequest.toast("已完成盘点，不可操作！")
					return false
				}
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						// console.log('条码类型：' + res.scanType);
						// console.log('条码内容：' + res.result);
						let data = {
							type: 8,
							warehouse_id:this.dataAll.warehouse.id,
							pd_id:that.listid,
							keyword:res.result
						}
						uni.navigateTo({
							url: '/pages/workbench/xiaoshou/tianjspxsdd?getmsg=' + encodeURIComponent(JSON.stringify(
								data))
						})
					},
					fail(err) {
						console.log('错误信息：' + err);
					}
				});
			},
			// 放弃仓库
			fangqck() {
				httpRequest.request('/dhtapi/Warehouse/deletePd', 'POST', {
					id:this.listid
				}, false, false, true).then(res => {
					if (res.code == 1) {
						httpRequest.toast(res.msg)
						setTimeout(function() {
							uni.navigateBack(1)
						}, 1000)
					} else {
						httpRequest.toast(res.msg)
					}

				})
			},
			// 完成盘点
			wancpd() {
				if(this.dataAll.pdgoods.length==0){
					httpRequest.toast("请选择盘点商品！")
					return false
				}
				httpRequest.request('/dhtapi/Warehouse/wcPd', 'POST', {
					id:this.listid
				}, false, false, true).then(res => {
					if (res.code == 1) {
						httpRequest.toast(res.msg)
						setTimeout(function() {
							uni.navigateBack(1)
						}, 1000)
					}

				})
			},
			
			dian() {
				this.selectshow = this.selectshow == false ? true : false
			},
		}
	}
</script>
<style lang="scss" scoped>
	.lablehuang{
		padding: 10rpx 30rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
		background-color: #faf3e7;
		color: #f4ae40;
	}
	.lablehong{
		padding: 10rpx 30rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
		background-color: rgba(255, 0, 0, .1);
		color: #ff0000;
	}
	.lablelan{
		padding: 10rpx 30rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
		background-color:rgba(32, 128, 240, .1);
		color: rgb(32, 128, 240);
	}
	.lablelv{
		padding: 10rpx 30rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
		background-color:rgba(26, 173, 125, .1);
		color: rgb(26, 173, 125);
	}
	.duihao {
		position: absolute;
		left: 20rpx;
		background-image: url('@/static/image/system/gouxuan.png');
		width: 30rpx;
		height: 30rpx;
		background-size: 100% 100%;
	}
	.qiantui {
		width: 45%;
		border-radius: 50rpx;
		height: 82rpx;
		font-size: 32rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}

	.greenbtn {
		background: #0BBDCB;
	}

	.reset {
		border: 1rpx solid #0BBDCB;
		color: #0BBDCB;
	}

	// 底部
	.huangse {
		font-size: 24rpx;
		text-align: center;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #F3AD3D;
	}

	.dibubox {
		position: fixed;
		
		width: 100%;
		left: 0;
		bottom: 0;
		box-sizing: border-box;
	}

	.onebox {
		margin: 0 30rpx;
		padding: 14rpx 0;
		background: rgba(243, 173, 61, .1);
		border-radius: 16rpx;
	}

	.dibubtn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 230rpx;
		height: 62rpx;
		border-radius: 74rpx;
		opacity: 1;
		border: 2rpx solid #0BBDCB;
	}

	.baise {
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #0BBDCB;
		margin-right: 10rpx;
	}

	.lansebtn {
		background: #0BBDCB;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
	.shanchu {
		background-image: url('@/static/image/system/shanchuer.png');
		width: 26rpx;
		height: 28rpx;
		background-size: 100% 100%;
	}

	.shangpinbox {
		padding-bottom: 240rpx;
	}

	.huisetext {
		font-size: 24rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #666666;
	}

	.xuanzsp {
		font-size: 28rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #0BBDCB;
	}

	.xiabk {
		padding-bottom: 30rpx;
		border-bottom: 2rpx solid rgba(153, 153, 153, 0.05);
	}

	.line {
		height: 38rpx;
		width: 2rpx;
		margin-right: 30rpx;
		background-color: rgba(0, 0, 0, 0.05);
	}

	.lanseyoujt {
		background-image: url('@/static/image/system/lanseyoutubiao.png');
		width: 12rpx;
		height: 22rpx;
		margin: 0 30rpx 0 10rpx;
		background-size: 100% 100%;
	}

	.dayinji {
		width: 40rpx;
		height: 40rpx;
		background-image: url("@/static/image/system/my2.png");
		background-size: 100% 100%;
	}

	// 定位点点点
	.diandiandian {
		position: relative;
	}

	.topbox {
		border-bottom: 2rpx solid rgba(255, 255, 255, .1);
	}

	.selectcontent {
		position: absolute;
		top: 50rpx;
		right: -6rpx;
		min-width: 200rpx;
		mix-width: 200rpx;
		text-align: center;
		background-color: rgba(11, 189, 203, 0.8);
		border-radius: 10rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #fff;
		word-wrap: break-word;
	}

	.sanjiao {
		position: absolute;
		top: -12rpx;
		right: 8rpx;
		background-image: url("@/static/image/system/sanjiao2.png");
		width: 40rpx;
		height: 12rpx;
		background-size: 100% 100%;
	}

	.itemselect {
		padding: 20rpx 30rpx;
	}

	/deep/.u-modal__content__text {
		text-align: center;
	}
</style>
